package solvers;

import java.util.HashSet;

import model.Graph;
import model.Itinerary;

public class BruteForceSolver extends Solver {

    private int[] solutionTmp;
    private int sumInSolutionTmp;

    public BruteForceSolver(Graph graph) {
        super(graph);
        solutionTmp = new int[graph.getSize()];
        sumInSolutionTmp = Integer.MAX_VALUE;
    }

    @Override
    public Itinerary solve() {
        solutionTmp[0] = 0;
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < graph.getSize() - 1; i++) {
            set.add(i + 1);
        }

        solve(solutionTmp, set, 1);
        return new Itinerary(solutionTmp, graph);
    }
    


    private void solve(int[] tab, HashSet<Integer> set, int index) {
       
        if (index == graph.getSize()) {          
            int sum = 0;
            for (int i = 0; i < tab.length - 1; i++) {
                sum += graph.get(tab[i], tab[i+1]);
            }
            sum += graph.get(tab[0], tab[tab.length - 1]);            
            if (sum < sumInSolutionTmp) {
                solutionTmp = tab.clone();
                sumInSolutionTmp = sum;
            }
            
        } else {
            for (Integer i : set) {
                tab[index] = i;
                @SuppressWarnings("unchecked")
                HashSet<Integer> newSet = (HashSet<Integer>) set.clone();
                newSet.remove(i);
                solve(tab, newSet, index + 1);
            }
        }
    }    
}
